﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Mime;

namespace FeedBack {
    public class DefaultLinkDownloader : IDownloader {

        public event EventHandler<StoryDownloadedEventArgs> Completed;

        public void Download(Story story) {
            string dir = Configuration.InProgressFolder;
            string filename = CandidateFileName(story);
            string path = Path.Combine(dir, filename);
            dir.EnsureDirectory();

            int i = 0;

            ThreadPool.QueueUserWorkItem((x) => {
                bool success = false;
                if (!Configuration.SkipDomains.Contains(story.Link.DnsSafeHost)) {
                    if (!Configuration.ProcessDomains.Any() ||
                        Configuration.ProcessDomains.Contains(story.Link.DnsSafeHost)) {
                        for (; File.Exists(path); ) {
                            Thread.Sleep(10000);
                            if (i++ > 3) {
                                break;
                            }
                        }

                        try {
                            MhtBuilder mht = new MhtBuilder();
                            mht.Save(story.Link, path);
                            if (File.Exists(path) && new FileInfo(path).Length > 0) {
                                var creationTime = DateTime.Parse(story.Json["created_time"] as string);
                                File.SetCreationTimeUtc(path, creationTime);
                                success = true;
                            }
                            else {
                                File.Delete(path);
                            }
                        }
                        catch {

                        }
                    }
                }
                if (Completed != null) {
                    Completed(this, new StoryDownloadedEventArgs { Filename = path, Story = story, Success = success });
                }
            });

        }

        public string CandidateFileName(Story story) {
            return Path.GetFileNameWithoutExtension(story.CandidateFileName(story.Link)) + ".mht";
        }

        public void PostProcess(string storyDirectory, Story story) {
            if (!string.IsNullOrWhiteSpace(story.Picture)) {
                string filename = CandidateFileName(story);
                string imageFile = Path.GetFileNameWithoutExtension(filename) + ".jpg";
                string imagePath = Path.Combine(storyDirectory, imageFile);
                WebDownload http = new WebDownload();
                http.DownloadFileCompleted += (a, b) => {
                    try {
                        var creationTime = DateTime.Parse(story.Json["created_time"] as string);
                        File.SetCreationTimeUtc(imagePath, creationTime);
                    }
                    catch { }
                };
                http.DownloadFileAsync(new Uri(story.Picture), imagePath);
            }
        }
    }
}
